package com.sca4cloud.sca.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
//@Order(1)
//@Component
//@WebFilter(urlPatterns = "/*")
public class UrlFilter implements Filter {

    private final static String[] URL_PREFIX = {"/admin/", "/gen/"};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void destroy() {}

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        System.out.println(httpRequest.getRequestURI());
        String path = httpRequest.getRequestURI();
        if (StrUtil.containsAny(path, URL_PREFIX)) {
            log.info("UrlFilter path={}", path);
            path ="/"+ removePrefix(path);
            httpRequest.getRequestDispatcher(path).forward(request, response);
        } else {
            chain.doFilter(request, response);

        }
        return;
    }

    public String removePrefix(String path) {
        for (String pre : URL_PREFIX) {
            if(StrUtil.startWith(path, pre))
                return StrUtil.removePrefix(path, pre);
            
        }
        return path;
    }

}
